import { buildPlanData, buildStationObjByData, getEditDisabled } from './helper';

export default {
  namespace: 'interprovincialSpotDeclaration',
  state: {
    startOrder: '',
    endOrder: '',
    provinceId: '', // 交易省份id
    date: '', // 交易日
    hourOrder: '', // 日内选择时间段
    selectedPlan: {}, // 已选计划
    type: 'dayahead', // 日前 dayahead 日内
    planData: [], // 查询返回的数据
    originalData: [],
    hasSave: true, // 通知参数，为true时通知全局有新方案已保存
    powerLimitInfo: [], // 权限
    marketList: [], //省份数组
    loadingNum: 0,
    sitelist: [], // 已选省份场站
    activeKey: '0', // 当前选中的方案
    stationObj: {}, // 每个标的日下的场站统一管理对象
    selectRowsObj: {}, // 以方案下策略的index值作为key选中的所有行数组作为value
    editDisabled: true, // 当前方案是否可编辑
    loading: true, // 方案加载的loading
  },
  reducers: {
    setPowerLimitInfo(state, { payload }) {
      return { ...state, powerLimitInfo: payload };
    },
    setAddLoadingNum(state) {
      return { ...state, loadingNum: state.loadingNum + 1 };
    },
    setSubLoadingNum(state) {
      return { ...state, loadingNum: state.loadingNum - 1 };
    },
    setSearchData(state, { payload }) {
      let sitelist = [];
      let selectedPlan = {};
      if (payload.marketId != state.marketId) {
        payload?.marketList.map((item) => {
          // 筛选场站
          if (item.value == payload.marketId) {
            sitelist = item.children;
          }
        });
      } else {
        sitelist = state.sitelist;
      }
      if (payload.planData.length > 0) {
        // 获得第一个方案
        selectedPlan = {
          name: payload.planData[0].latestOperateLog?.operateUserName,
          saveDate: payload.planData[0].latestOperateLog?.operateTime,
          plan: payload.planData[0]?.title,
        };
      } else {
        selectedPlan = state.selectedPlan;
      }
      const stationObj = buildStationObjByData(payload.planData || []);
      const planData = buildPlanData(payload.planData || []);
      const activeKey = planData[+state.activeKey] ? state.activeKey : '0';
      const editDisabled = getEditDisabled(payload.planData, activeKey);
      return {
        ...state,
        ...payload,
        sitelist,
        selectedPlan,
        stationObj,
        planData,
        editDisabled,
        originalData: payload.planData,
        activeKey,
      };
    },
    setState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
